package com.xp.agent.task;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.xp.agent.common.CommonProperties;
import com.xp.agent.common.MessageQueue;
import com.xp.agent.dto.AlarmMessage;

public class FileLogTask implements Runnable {

	@Override
	public void run() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		while (true) {
			File parentFile = new File(CommonProperties.logPath.get());
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			AlarmMessage message = MessageQueue.getInstance().poll();
			if (message == null) {
				continue;
			}
			String fileName = sdf.format(new Date(message.getTime())) + "-xp.log";
			File logFile = new File(parentFile, fileName);
			try (PrintStream pw = new PrintStream(new FileOutputStream(logFile, true));) {
				pw.printf("%-15s  发生时间：%-15s当前值:%-15s阈值:%-15s\n", message.getItem(), message.getFormatTime(),
						message.getValue(), message.getThreshold());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

		}

	}

}
